﻿using System;
using System.Windows.Forms;

namespace SwitchNet
{
    public delegate void StatusUpdate( string message );
    
    class NICProfileManager
	{
		#region Variables

		private NICProfile _NICProfile;

		public event StatusUpdate OnStatusUpdate;

		#endregion

		#region Constructors
		
		public NICProfileManager( NICProfile nicProfile )
		{
            _NICProfile = nicProfile;
		}

		#endregion

		#region Public Methods

        public void Run()
        {
            applyNIC(_NICProfile);
        }

		#endregion

		#region Private methods

		/// <summary>
		/// Applies configuration for the specified NIC
		/// </summary>
		/// <param name="nicName"></param>
        private void applyNIC( NICProfile nicProfile )
		{
            string nicName = nicProfile.Name;

			if( null == nicProfile )
                return;

			//UpdateStatus( "Setting configuration for: " + nicName );

			try
			{
                if (nicProfile.UseDHCP)
                {
                    NetworkManagement.SetDHCP(nicName);
                    UpdateStatus("启动自动获得IP地址(DHCP).");
                }
                else
                {
                    NetworkManagement.SetIPAddress(nicProfile);

                    UpdateStatus("关闭自动获得IP地址(DHCP).");
                }
			}
			catch( Exception x )
			{
				UpdateStatus( "网络配置出错." );
				UpdateStatus( x.Message );
				return;
			}

            UpdateStatus("完成.");
            UpdateStatus("点击[确定]继续 ...");
		}

		/// <summary>
		/// Raises event to update status
		/// </summary>
		/// <param name="message"></param>
		private void UpdateStatus( string message )
		{
			if( null != OnStatusUpdate )
				OnStatusUpdate( message + Environment.NewLine );
		}
		
		#endregion
	}
}
